//
//  GBShortMessageTableView.m
//  PublicSentimentMonitorSystem
//
//  Created by 郭斌 on 15/11/13.
//  Copyright © 2015年 魏强. All rights reserved.
//

#import "GBShortMessageTableView.h"
#import "GBShortMessageTableViewCell.h"
#import "GBRequest.h"
#import "MJRefresh.h"
#import "SVProgressHUD.h"
#import "GBModel.h"

#define baseUrl @"&method=getReportShortMessageList&token="
#define page @"&p="
#define limit @"&limit=10"

@interface GBShortMessageTableView ()<UITableViewDataSource,UITableViewDelegate,GBRequestDelegate>
{
    NSMutableArray *dataArray; //数据源
    int allCount; //所有数据的个数
    int limitCount; //现在数据的条数
    //记录每个tableview的当前页
    int _currentPage;
    NSString *refreshUrl; //下拉加载更多的url
}

/**
 *  没有数据时的提示
 */
@property (nonatomic, weak) UIView * notice;

@end

@implementation GBShortMessageTableView
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
        KDAccount *account = [KDAccountTool account];
        _Jurl = [NSString stringWithFormat:@"%@%@%@%@", ServerActionAddr, baseUrl, account.tokens,@"&p=1&limit=10"];
        //初始化
        self.rowHeight = 100;
        dataArray = [NSMutableArray array];
        self.tableFooterView = [[UIView alloc] init];
        self.delegate = self;
        self.dataSource = self;
        [self registerClass:[GBShortMessageTableViewCell class] forCellReuseIdentifier:@"Cell"];
        //去掉下划线
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        //请求数据
        [self lateeeee];
        
//        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.7 target:self selector:@selector(lateeeee) userInfo:nil repeats:NO];
    }
    return self;
}

#pragma mark - 延时
-(void)lateeeee
{
    //    __weak typeof(self) weakSelf = self;
    
    // 添加传统的下拉刷新
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(startRequest)];
    // 马上进入刷新状态
    [self.header beginRefreshing];
    // 添加传统的上拉刷新
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    MJRefreshAutoNormalFooter *fooder = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [fooder setTitle:@"" forState:MJRefreshStateIdle];
    self.footer = fooder;
    // 添加传统的上拉刷新
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    /**
     也可以这样使用
     [self.tableView.header beginRefreshing];
     此时self.tableView.header == self.tableView.legendHeader
     */
}

#pragma mark - 上拉加载更多
-(void)loadMoreData
{
    //判断当前是否有新数据
    if(limitCount < allCount)
    {
        limitCount += 10;
        _currentPage++;
        [self startRequest2];
    }
    else
    {
        [self.footer endRefreshing];
    }
}

#pragma mark - 开始请求数据
-(void)startRequest
{
    //重新刷新 重置数据
    limitCount = 10;
    _currentPage = 1;
    //检查当前网络状态
    
    //清空数组
    [dataArray removeAllObjects];
    //NSLog(@"基本url:%@",_Jurl);
    GBRequest *request1 = [[GBRequest alloc]initWithUrlStr:_Jurl];
    request1.tag = 1;
    request1.delegate = self;
    [request1 startRequestData];
}

#pragma mark - 上拉加载更多数据
-(void)startRequest2
{
    KDAccount *account = [KDAccountTool account];
    refreshUrl = [NSString stringWithFormat:@"%@%@%@%@%d%@&count=%d", ServerActionAddr, baseUrl,account.tokens,page,_currentPage,limit,allCount];
    //NSLog(@"###2 %@",refreshUrl);
    GBRequest *request1 = [[GBRequest alloc]initWithUrlStr:refreshUrl];
    request1.tag = 1;
    request1.delegate = self;
    [request1 startRequestData];
}

#pragma mark - 数据成功请求完毕
- (void)requestDidFinished:(GBRequest *)request
{
    [self.notice removeFromSuperview];
    
    NSString *str = [[NSString alloc] initWithData:request.requestData encoding:NSUTF8StringEncoding];
    //解析
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    id dataArrayJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSDictionary *jsonDict = nil;
    if ([dataArrayJson isKindOfClass:[NSDictionary class]])
    {
        jsonDict = dataArrayJson;
    }
    //NSLog(@"%@",jsonDict[@"info"]);
    //数据总个数
    if([jsonDict[@"count"] isKindOfClass:[NSNumber class]])
    {
        id countAll = jsonDict[@"count"];
        allCount = [countAll intValue];
    }
    
    if(allCount == 0)
    {
        //设置没有数据的界面
        [self setUpNotise];
    }
    
    NSMutableArray *info = jsonDict[@"info"];
    for(NSDictionary *dic in info)
    {
        GBModel *model = [[GBModel alloc] init];
        //标题
        model.title = [NSString stringWithFormat:@"%@", dic[@"text"]];
        
        //时间
        long long time= [dic[@"time"] longLongValue ];
        NSDate *d = [[NSDate alloc] initWithTimeIntervalSince1970:time/1000.0];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *strDate = [dateFormatter stringFromDate:d];
        model.date = [NSString stringWithFormat:@"%@",strDate];
        
        [dataArray addObject:model];
    }
    
    [self reloadData];
    //停止更新数据
    [self.header endRefreshing];
    [self.footer endRefreshing];
}

#pragma mark - 数据请求失败
- (void)requestDidFailedWithError:(NSError *)error
{
    [SVProgressHUD showErrorWithStatus:@"请求失败" maskType:SVProgressHUDMaskTypeGradient];
    //停止更新数据
    [self.header endRefreshing];
    [self.footer endRefreshing];
}

#pragma mark - tableview返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    GBShortMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    if(dataArray.count > 0)
    {
        //NSLog(@"%@",kindArr);
        GBModel *model = dataArray[indexPath.row];
        cell.titleLabel.text = model.title;
        cell.TimeLabel.text = model.date;
        //定制cell右按钮
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return cell;
}

- (void)setUpNotise
{
    UIView * notice = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenW, screenH -40- 49 - 64 )];
    
    self.notice = notice;
    UIButton * noticeLb = [[UIButton alloc]init];
    noticeLb.frame = notice.bounds;
    notice.backgroundColor = BackGroundColor;
    [noticeLb setTitle:@"暂时没有满足条件的数据！" forState:UIControlStateNormal];
    noticeLb.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

    [noticeLb setTitleColor:WQColor(178, 182, 184) forState:UIControlStateNormal];
    [noticeLb addTarget:self action:@selector(startRequest) forControlEvents:UIControlEventTouchUpInside];
    [notice addSubview:noticeLb];
    [self.superview insertSubview:notice atIndex:1];
}

#pragma mark - 当单元格被选中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //NSString *indexT = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
